﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace DataGridViewDataSource
{
    public static class ConvertDataTableHelper
    {

        public static List<T> DataTableToList<T>(DataTable dt) where T : new()
        {
            List<T> list = new List<T>();
            T t = new T();
            PropertyInfo[] propertypes = null;
            string tempName = string.Empty;

            foreach (DataRow row in dt.Rows)
            {
                t = Activator.CreateInstance<T>();
                propertypes = t.GetType().GetProperties();

                foreach (PropertyInfo pro in propertypes)
                {
                    tempName = pro.Name;
                    if (dt.Columns.Contains(tempName))
                    {
                        object value = row[tempName];
                        if (!value.ToString().Equals(""))
                        {
                            pro.SetValue(t, row[tempName]);
                        }
                    }
                }

                list.Add(t);
            }

            return list.Count == 0 ? null : list;
        }

        public static ArrayList DataTableToArrayList<T>(DataTable dt) where T : new()
        {
            ArrayList list = new ArrayList();
            T t = new T();
            PropertyInfo[] propertypes = null;
            string tempName = string.Empty;

            foreach (DataRow row in dt.Rows)
            {
                t = Activator.CreateInstance<T>();
                propertypes = t.GetType().GetProperties();

                foreach (PropertyInfo pro in propertypes)
                {
                    tempName = pro.Name;
                    if (dt.Columns.Contains(tempName))
                    {
                        object value = row[tempName];
                        if (!value.ToString().Equals(""))
                        {
                            pro.SetValue(t, row[tempName]);
                        }
                    }
                }

                list.Add(t);
            }

            return list.Count == 0 ? null : list;
        }

        /// <summary>
        /// datatable转List<Hashtable>
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static List<Hashtable> DataTableToListHashtable(DataTable dt)
        {
            List<Hashtable> hsList = new List<Hashtable>();

            foreach (DataRow row in dt.Rows)
            {
                var hashtable = new Hashtable();
                foreach (DataColumn column in dt.Columns)
                {
                    hashtable.Add(column.ColumnName, row[column]);
                }
                hsList.Add(hashtable);
            }

            return hsList;
        }

    }
}
